//
//  HomePageViewController.m
//  Kids
//
//  Created by tengfei on 14/11/22.
//  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
//

#import "HomePageViewController.h"
#import "DeviceListView.h"
#import "AccountInfo.h"

#import "LoginViewController.h"
#import "WatchListRequestData.h"
#import "WatchListResponseData.h"
#import "RequestFactory.h"
#import "NSString+md5.h"

#import "CustomAnnotationView.h"
#import "WatchLocationRequestData.h"
#import "WatchLocationResponseData.h"

#import "SVProgressHUD.h"


#import "DeviceEditView.h"


@interface HomePageViewController () <MAMapViewDelegate, DeviceDelegate, DeviceDataSource>
@property (nonatomic, strong) MAGroundOverlay* currenOverlay;
@property (nonatomic, strong) MAPointAnnotation* annotation;
@property (nonatomic,assign) CGFloat scale;

@end

@implementation HomePageViewController
- (instancetype)init
{
    if (self = [super init]) {
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        //如果 账号 没有登录  登陆
    if ([AccountInfo shareInstance].LoginState == LoginStateOutline) {
        LoginViewController * loginViewController  = [[LoginViewController alloc]init];
        
        UINavigationController * nvc =[[UINavigationController alloc]initWithRootViewController:loginViewController];
        nvc.navigationBarHidden = YES;
        [self presentViewController:nvc animated:NO completion:nil];
        
    }else{
        [self refreashWatchData];
    }
}

- (void)viewDidLoad
{
    self.scale = 0.1;
    [super viewDidLoad];
    self.annotation = [[MAPointAnnotation alloc] init];

    self.watchDataArray = [[NSMutableArray alloc] initWithCapacity:0];

    self.mapView = ({
        MAMapView * mapView = [[MAMapView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        mapView.showsUserLocation = YES;
        mapView.showsCompass = NO;
        mapView.delegate = self;
        mapView.zoomLevel = 13;
        [mapView setUserTrackingMode:MAUserTrackingModeFollow];
        mapView;
    });

    [self.view addSubview:self.mapView];

    self.deviceListView = [[DeviceListView alloc] initWithFrame:CGRectMake(0, 300, CGRectGetWidth(self.view.frame), 60)];
    self.deviceListView.dataSource = self;
    self.deviceListView.delegate = self;
    [self.deviceListView showInView:self.view];
    
        //如果 账号 没有登录  登陆
    if ([AccountInfo shareInstance].LoginState == LoginStateOnline) {
        [self refreashWatchData];
    }
}

- (void)refreashWatchData
{

    WatchListRequestData* data = [[WatchListRequestData alloc] init];

    AccountInfo * info =     [AccountInfo shareInstance];
    
    NSAssert(info.phone.length>0, @"number must not be nil");
    NSAssert(info.password.length > 0, @"password not be nil");
    
    data.phone = info.phone;
    data.password = [info.password md5];

    WatchListResponseData* responseData = [[WatchListResponseData alloc] init];

    [RequestFactory requestWithRequestData:data forResponseData:responseData complete:^(ResponseData* responseData, NSError* error) {
        NSLog(@"%@",responseData.info);
        if(responseData.result ==0){
            [SVProgressHUD showImage:nil status:@"没有存在的设备"];
        }else{
            NSLog(@"%ld",(unsigned long)[[(WatchListResponseData *)responseData modelList] count]);
            
            [self.watchDataArray removeAllObjects];
            [self.watchDataArray addObjectsFromArray:[(WatchListResponseData *)responseData modelList]];
        
            [self.deviceListView reload];
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - map delegate
- (MAAnnotationView*)mapView:(MAMapView*)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {

        static NSString* customReuseIndetifier = @"customReuseIndetifier";

        CustomAnnotationView* annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];

        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }

        annotationView.portrait = [UIImage imageNamed:@"photo_size"];
        annotationView.name = @"河马";

        return annotationView;
    }

    return nil;
}

#pragma mark -deviceDataSource

- (NSInteger)numberOfDeviceView
{
    return self.watchDataArray.count;
}

- (DeviceView*)deviceListView:(DeviceListView*)deviceListView deviceViewForDeviceListViewIndex:(NSInteger)index
{
    DeviceView* deviceView = [[DeviceView alloc] init];
    WatchModel* model = [self.watchDataArray objectAtIndex:index];
    if([model.wstate isEqual:@"1"]){
        deviceView.enabled =YES;
    }else{
        deviceView.enabled = NO;
    }
    deviceView.deviceData = model;
    return deviceView;
}
- (CGFloat)deviceListView:(DeviceListView*)deviceListView heightForDeviceViewAtIndex:(NSInteger)index
{
    return 50;
}
- (CGFloat)deviceListView:(DeviceListView*)deviceListView heightForHeaderViewAtIndex:(NSInteger)index
{
    return 10;
}
- (CGFloat)deviceListView:(DeviceListView*)deviceListView heightForFooterViewAtIndex:(NSInteger)index
{
    return 10;
}

- (void)deviceListView:(DeviceListView*)deviceListView didSelectDeviceAtIndex:(NSInteger)index
{

    [self.mapView removeAnnotation:self.annotation];

    WatchModel* model = [self.watchDataArray objectAtIndex:index];

    NSLog(@"%@", model.wstate);
    
    if(![model.wstate isEqualToString:@"1"]){
        [SVProgressHUD showImage:nil status:@"此用户不在线"];
        return;
    }

    AccountInfo* info = [AccountInfo shareInstance];

    NSParameterAssert(info.password);
    NSParameterAssert(info.phone);

    WatchLocationRequestData* requestData = [[WatchLocationRequestData alloc] init];
    requestData.imei = model.wimei;
    requestData.pphone = info.phone;
    requestData.ppwd = [info.password md5];

    WatchLocationResponseData* responseData = [[WatchLocationResponseData alloc] init];

    [RequestFactory requestWithRequestData:requestData forResponseData:responseData complete:^(ResponseData* responseData, NSError* error) {
        WatchLocationResponseData * response = (WatchLocationResponseData*)responseData;
        
        WatchLocationModel * location = response.model;
        if(location.GPS.length ==0){
            [SVProgressHUD showImage:nil status:@"没有获取到位置信息"];
        }else{
            self.annotation.coordinate = location.coordinate;
            self.annotation.title    = @"AutoNavi";
            self.annotation.subtitle = @"CustomAnnotationView";
        
            [self.mapView addAnnotation:self.annotation];
        
            [self.mapView setRegion:MACoordinateRegionMake(location.coordinate, MACoordinateSpanMake(self.scale, self.scale)) animated:YES];
        }
    }];
}
- (IBAction)refreashButtonClick:(UIBarButtonItem*)sender
{
    [self refreashWatchData];
}
-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
    self.scale = 1/mapView.zoomLevel;
}
@end
